package com.infore.airsupervise.adapter;

import android.support.annotation.IdRes;
import android.view.View;
import android.view.ViewGroup;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RadioGroup;

import com.alibaba.fastjson.JSON;
import com.chad.library.adapter.base.BaseMultiItemQuickAdapter;
import com.chad.library.adapter.base.BaseViewHolder;
import com.chad.library.adapter.base.entity.MultiItemEntity;
import com.infore.airsupervise.R;
import com.infore.airsupervise.app.StatusConst;
import com.infore.airsupervise.bean.DispatchAqiChartE;
import com.infore.airsupervise.bean.DispatchAqiE;
import com.infore.airsupervise.bean.DispatchAqiExpandE;
import com.infore.airsupervise.bean.DispatchWeatherE;
import com.infore.airsupervise.bean.DispatchWeatherExpandE;
import com.infore.airsupervise.utils.AirLevelUtil;

import java.util.List;

import info.hoang8f.android.segmented.SegmentedGroup;

/**
 * 实时调度-气象数据-扩展列表适配器
 * <p>
 * 作者: dingxinlin
 * 创建日期: 2017/8/18 17:51
 */

public class DispatchWeatherExpendAdapter
        extends BaseMultiItemQuickAdapter<MultiItemEntity, BaseViewHolder> {

    public static final int TYPE_LEVEL_0 = 0;
    public static final int TYPE_LEVEL_1 = 1;

    public int dataType = 0; // 外部设置的数据类型

    /**
     * Same as QuickAdapter#QuickAdapter(Context,int) but with
     * some initialization data.
     *
     * @param data A new list is created out of this one to avoid mutable list
     */
    public DispatchWeatherExpendAdapter(List<MultiItemEntity> data) {
        super(data);
        addItemType(TYPE_LEVEL_0, R.layout.item_dispatch_weather);
        addItemType(TYPE_LEVEL_1,R.layout.item_dispatch_weather_expend);
    }

    @Override
    protected void convert(final BaseViewHolder helper, MultiItemEntity item) {

        switch (helper.getItemViewType()) {
            case TYPE_LEVEL_0:
                convertFactorItem(helper, item);
                break;

            case TYPE_LEVEL_1:
                convertChartItem(helper, item);
                break;
        }
    }

    /**
     * 因子item设值
     * @param helper
     * @param item
     */
    private void convertFactorItem(final BaseViewHolder helper, MultiItemEntity item) {
        final DispatchWeatherExpandE weatherExpand = (DispatchWeatherExpandE) item;
        DispatchWeatherE.WeatherBean nearData = weatherExpand.nearData;

        // 气象参数、时间
        helper.setText(R.id.station_name, weatherExpand.staName);
        helper.setText(R.id.data_time, nearData.getTime());

        // 因子参数
        helper.setText(R.id.tv_temperature,  nearData.getTemperature() + "℃");
        helper.setText(R.id.tv_humidity,  nearData.getHumidity() + "%");
        helper.setText(R.id.tv_pressure,  nearData.getPressure() + "hpa");
        helper.setText(R.id.tv_direction, nearData.getSpeedDirCn());
        helper.setText(R.id.tv_angle,  nearData.getSpeedDir() + "°");
        helper.setText(R.id.tv_speed,  nearData.getSpeed() + "m/s");
        helper.setText(R.id.tv_rain,  nearData.getRain() + "mm");

        // item点击事件
        helper.itemView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                int pos = helper.getAdapterPosition();
                if (weatherExpand.isExpanded()) {
                    collapse(pos);
                } else {
                    expand(pos);
                }
            }
        });
    }

    /**
     * 转换图表item
     * @param helper
     * @param item
     */
    private void convertChartItem(BaseViewHolder helper, MultiItemEntity item) {
        final DispatchWeatherExpandE.FactorTrendE factorTrend = (DispatchWeatherExpandE.FactorTrendE) item;

        // 实例WebView
        final WebView mWebView = new WebView(this.mContext.getApplicationContext());

        // 将WebView加入容器
        FrameLayout webContainer = helper.getView(R.id.web_container);
        LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(
                ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT);
        mWebView.setLayoutParams(layoutParams);
        webContainer.addView(mWebView);

        // 配置WebView
        WebSettings settings = mWebView.getSettings();
        settings.setJavaScriptEnabled(true);
        settings.setAllowFileAccess(true);
        settings.setDomStorageEnabled(false);
        settings.setAppCacheEnabled(false);
        mWebView.setLayerType(View.LAYER_TYPE_SOFTWARE, null);

        // 不用系统浏览器打开,直接显示在当前WebView
        mWebView.setWebViewClient(new WebViewClient(){
            @Override
            public void onPageFinished(WebView view, String url) {
                super.onPageFinished(view, url);
                mWebView.loadUrl("javascript:refresh('"
                        + getChartNeedData(0, factorTrend.dataList) + "')");
            }
        });

        // 加载网页文件
        mWebView.loadUrl("file:///android_asset/chart-dispatch-aqi.html");

        // 因子切换处理
        SegmentedGroup segGroup = helper.getView(R.id.segment_weather);
        segGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup radioGroup, @IdRes int i) {
                switch (i) {
                    case R.id.rb_temperature:
                        mWebView.loadUrl("javascript:refresh('"
                                + getChartNeedData(0, factorTrend.dataList) + "')");
                        break;
                    case R.id.rb_humidity:
                        mWebView.loadUrl("javascript:refresh('"
                                + getChartNeedData(1, factorTrend.dataList) + "')");
                        break;
                    case R.id.rb_pressure:
                        mWebView.loadUrl("javascript:refresh('"
                                + getChartNeedData(2, factorTrend.dataList) + "')");
                        break;
                    case R.id.rb_direction:
                        mWebView.loadUrl("javascript:refresh('"
                                + getChartNeedData(3, factorTrend.dataList) + "')");
                        break;
                    case R.id.rb_speed:
                        mWebView.loadUrl("javascript:refresh('"
                                + getChartNeedData(4, factorTrend.dataList) + "')");
                        break;
                    case R.id.rb_rain:
                        mWebView.loadUrl("javascript:refresh('"
                                + getChartNeedData(5, factorTrend.dataList) + "')");
                        break;
                }
            }
        });
        segGroup.check(R.id.rb_temperature);
    }

    /**
     * 转换为图标需要的数据格式
     * @param dataList
     */
    private String getChartNeedData(int factorType, List<DispatchWeatherE.WeatherBean> dataList) {

        DispatchAqiChartE chartE = new DispatchAqiChartE();

        // 标题信息
        String[] titles = getChartTitle(dataType, factorType);
        chartE.setTitle(titles[0]);
        chartE.setSeriesName(titles[1]);

        // X\Y轴信息
        for (DispatchWeatherE.WeatherBean data : dataList) {
            chartE.getCategories().add(data.getTime());

            switch (factorType) {
                case 0 :
                    chartE.getSeriesData().add(data.getTemperature());
                    break;
                case 1 :
                    chartE.getSeriesData().add(data.getHumidity());
                    break;
                case 2 :
                    chartE.getSeriesData().add(data.getPressure());
                    break;
                case 3 :
                    chartE.getSeriesData().add(data.getSpeedDir());
                    break;
                case 4 :
                    chartE.getSeriesData().add(data.getSpeed());
                    break;
                case 5 :
                    chartE.getSeriesData().add(data.getRain());
                    break;
            }
        }
        return JSON.toJSONString(chartE);
    }

    /**
     * 获取图表标题
     * @param dataType
     * @param factorType
     */
    private String[] getChartTitle(int dataType, int factorType) {
        String[] timeStrs = new String[]{"近4小时", "近24小时", "近30天"};
        String[] factorStrs = new String[]{"温度", "湿度", "大气压", "风向", "风速", "降雨量"};

        String factorName = "";
        StringBuffer stringBuffer = new StringBuffer();

        for (int i=0; i<timeStrs.length; i++) {
            if (i == dataType) {
                stringBuffer.append(timeStrs[i]);
                break;
            }
        }

        for (int j=0; j<factorStrs.length; j++) {
            if (j == factorType) {
                stringBuffer.append(factorStrs[j]);
                factorName = factorStrs[j];
                break;
            }
        }
        stringBuffer.append("变化趋势");

        return new String[]{stringBuffer.toString(), factorName};
    }
}
